package at.fhooe.mc.msports;

import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.Statement;
import net.rim.device.api.io.URI;

/**
 * Simple class which provides all functionalities to check if a
 * database already exists on the local device, create and delete
 * a database or to open an existing one.
 *
 */
public class DBDaemon {
	
	public static final String FILE_URL = "file:///SDCard/Databases/SQLite_Guide/PedoDB15.db";

	
	public static boolean isDatabaseAlive(){
		try {
			URI uri = URI.create(FILE_URL);
			return DatabaseFactory.exists(uri);
		} catch (Exception e) {
			return false;
		}
	}
	
	public static Database openDatabase(){
		try {
			URI uri = URI.create(FILE_URL);
			return DatabaseFactory.open(uri);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static Database createDatabase(){
		try {
			URI uri = URI.create(FILE_URL);
			Database d = DatabaseFactory.create(uri);
			
			//create table
			Statement stmt = d.createStatement("CREATE TABLE 'Session' ( "
					+ "'Timestamp' INT8, " +
					"'Steps' INTEGER, " +
					"'Distance' REAL, " +
					"'Speed' REAL, " +
					"'Heartrate' INTEGER, " +
					"'Frequency' REAL, " +
					"'Duration' INT8, " +
					"'Calories' REAL," +
					"'AvgHeartrate' INTEGER," +
					"'MinHeartrate' INTEGER," +
					"'MaxHeartrate' INTEGER," +
					"'PercentageHRMax' INTEGER," +
					"'Trimp' REAL)");
			stmt.prepare();
			stmt.execute();
			stmt.close();
			Statement stmt2 = d.createStatement("CREATE TABLE 'PersonalData' ( "
					+ "'Height' REAL, " +
					"'Weight' REAL, " +
					"'Age' INT8, " +
					"'GPS' BOOLEAN," +
					"'MALE' BOOLEAN," +
					"'Zone' INT8)");
			stmt2.prepare();
			stmt2.execute();
			stmt2.close();
			return d;
		} catch (Exception e) {
			return null;
			}	
	}
	
	public static void deleteDatabase(){
		try {
			URI uri = URI.create(FILE_URL);
			DatabaseFactory.delete(uri);
		} catch (Exception e) {}
	}
	
}
